package com.example.yelp.service;

import java.util.ArrayList;

import org.scribe.builder.ServiceBuilder;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;

//import android.util.Log;

import android.util.Log;

import com.example.yelp.service.beans.*;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class YelpService 
{
  private static Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
  private static Yelp_Constant yelpc = new Yelp_Constant();
 
  /*
   * Yelp API Search function
   */
  public YelpSearchResult search(Double lat, Double lng, String location, String term, String category_filter, int radius, int limit, int offset,
      String sort) {
	 
    String endpoint = "http://api.yelp.com/v2/search";
    OAuthService service = new ServiceBuilder().provider(YelpApi2.class).apiKey(
    		yelpc.getYelpConsumerKey()).apiSecret(yelpc.getYelpConsumerSecret()).build();
    
    Token accessToken = new Token(yelpc.getYelpToken(), yelpc.getYelpTokenSecret());
    
    OAuthRequest request = new OAuthRequest(Verb.GET, endpoint);
    
    if (lat != null && lng != null) {
      request.addQuerystringParameter("ll", lat + "," + lng);
    }
    if (location != null && location.trim().length() > 0) {
      request.addQuerystringParameter("location", location.replaceAll("\n", ", "));
    }
    if (term != null) {
      request.addQuerystringParameter("term", term);
    }
    if (category_filter != null) {
      request.addQuerystringParameter("category_filter", category_filter);
    }
    request.addQuerystringParameter("radius", Integer.toString(radius));
    request.addQuerystringParameter("limit", Integer.toString(limit));
    request.addQuerystringParameter("offset", Integer.toString(offset));
    request.addQuerystringParameter("sort", sort);

    service.signRequest(accessToken, request); 
    
    Response response = null;
    try
    {
    	response = request.send();
    }
    catch(Exception e)
    {
    	Log.d("Exception", e.getMessage());
    }
    
    Log.d("Request","Request Sent");
    String jsonResult = response.getBody();
    Log.d(YelpService.class.getName(), "Response: " + jsonResult);
    System.out.println("Response: " + jsonResult);
    YelpSearchResult places = null;
    try {
      places = gson.fromJson(jsonResult, YelpSearchResult.class);
    } catch (JsonSyntaxException ex) {
      Log.e(YelpService.class.getName(), ex.getCause() + " : " + ex.getLocalizedMessage());
    }
    return places;
  }
  
  /*
   * Get all restaurant details
   */
  public YelpSearchResult getAllRestaurantData(String term,double latitude, double longitude)
  {
	YelpService yelp = new YelpService();
	
    YelpSearchResult result = new YelpSearchResult();

    result = yelp.search(latitude, longitude, "", term, null, 10, 15, 0, "0");
    
    return result;
  }
  
  /*
   * Get Restaurant Details based on category
   */
  public YelpSearchResult getRestaurantForCategory(String term, String category,double latitude, double longitude)
  {
    YelpService yelp = new YelpService();

    YelpSearchResult result = new YelpSearchResult();
    Log.d("Yelp Service","Inside YelpService");
    Log.d("Latitude Value", Double.toString(latitude));
    Log.d("Longitude Value", Double.toString(longitude));
    Log.d("Term Value", term);
    Log.d("category Value", category);
    result = yelp.search(latitude, longitude, "", term, null, 10, 15, 0, "0");
           
    YelpSearchResult narrowedSearchResult = new YelpSearchResult() ;
    ArrayList<Business> newList = new ArrayList<Business>();
    for(int i=0; i< result.getBusinesses().size();i++)
    {
    	for(int j=0;j< result.getBusinesses().get(i).getCategories().size();j++)
    	{
    		if(result.getBusinesses().get(i).getCategories().get(j).get(0).compareToIgnoreCase(category) == 0)
    		{
    			newList.add(result.getBusinesses().get(i));
    		}
    	}
    }
    narrowedSearchResult.setBusinesses(newList);

    return narrowedSearchResult;
  }
}